package com.scsj.supermarket.view.fragment.fivepagemodel;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.scsj.supermarket.R;
import com.scsj.supermarket.base.TradeAreaBase;
import com.scsj.supermarket.bean.NearByTradeAreaBean;
import com.scsj.supermarket.config.RxSPConfig;
import com.scsj.supermarket.event.FirstEvent;
import com.scsj.supermarket.presenter.NearByTradeAreaPresenter;
import com.scsj.supermarket.utils.BaiduMapHelper;
import com.scsj.supermarket.utils.RxBus;
import com.scsj.supermarket.utils.SkipUtils;
import com.scsj.supermarket.view.fragment.basemodel.BaseFragment;
import com.vondear.rxtools.RxPermissionsTool;
import com.vondear.rxtools.RxSPTool;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 地图定位页面
 */
public class MapFragment extends BaseFragment implements View.OnClickListener, TradeAreaBase.IView {
    private NearByTradeAreaPresenter nearByTradeAreaPresenter;
    private List<NearByTradeAreaBean.DataBean> tradeAreaList = new ArrayList();
    private List<NearByTradeAreaBean.DataBean.SimpleStoreInfoListBean> StoreInfoList = new ArrayList();

    /**
     * 地图相关
     */
    private MapView baiduMapView;
    private BaiduMap mBaiduMap;
    private ImageView middleIv, resetIv;
    public BDLocation mLocation;
    private float zoom = 16;
    private LatLng myPosition;
    private RelativeLayout searchTradeArea;
    /**
     *地图相关
     */

    /**
     * 店铺信息弹窗相关控件
     */
    private ImageView mDCover;
    private ImageView mDShopImg;
    private TextView mDName;
    private TextView mDScore;
    private TextView mDAddress;
    private Button mDEnterShop;
    private RatingBar mDRatingBar;
    private TextView mDGoodsNum;
    private ImageView mPayBound;
    private Dialog mDialog;

    /**
     * 店铺信息弹窗相关控件
     */
    private EditText searchMapEt;
    private String searchText;
    private ImageView mapSearchImg;
    private double lat;
    private double lon;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_map, null);
        RxPermissionsTool.with(getHoldingActivity())
                .addPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                .initPermission();
        initView(inflate, null);
        initData();
        initListener();
        return inflate;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        searchMapEt= view.findViewById(R.id.et_search_key);
        mapSearchImg= view.findViewById(R.id.map_search_img);
        nearByTradeAreaPresenter = new NearByTradeAreaPresenter(this);
        searchTradeArea = view.findViewById(R.id.map_trade_search_ll);
        baiduMapView = view.findViewById(R.id.b_mapView);
        mBaiduMap = baiduMapView.getMap();

        BaiduMapHelper
                .getInstance()
                .init(baiduMapView)
                .params(getHoldingActivity())
                .showLocation();

        middleIv = view.findViewById(R.id.middle_location_iv);
        resetIv = view.findViewById(R.id.reset_location_iv);

        //搜索框设置文字输入监听
        searchMapEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                //文字输入后监听
                searchText= editable.toString();
                if (TextUtils.isEmpty(searchText)){
                    searchMapEt.setCursorVisible(false);
                    mapSearchImg.setVisibility(View.VISIBLE);
                }else {
                    searchMapEt.setCursorVisible(true);
                    mapSearchImg.setVisibility(View.GONE);
                }
                //查询商圈
                lat= Double.parseDouble(RxSPTool.getString(getHoldingActivity(), RxSPConfig.LAT));
                lon= Double.parseDouble(RxSPTool.getString(getHoldingActivity(),RxSPConfig.LON));
                getLocationInfo(lat,lon,searchText);
            }
        });

        searchMapEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchMapEt.setCursorVisible(true);
                mapSearchImg.setVisibility(View.GONE);
            }
        });

    }

    @Override
    protected void initListener() {
        resetIv.setOnClickListener(this);
        searchTradeArea.setOnClickListener(this);
        /**
         地图状态改变监听
         */
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus arg0) {
//                //地图状态改变，取消网络请求
//                if (cancelable!=null && !cancelable.isCancelled())
//                    cancelable.cancel();
//                mImageView.startAnimation(animation);
                startAnima();
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus arg0) {
                startAnima2();
                Point point = new Point();
                int[] location = new int[2];
                middleIv.getLocationOnScreen(location);
                point.x = location[0] - middleIv.getWidth() / 2;
                point.y = location[1];
                zoom = arg0.zoom;

                LatLng latLng = mBaiduMap.getProjection().fromScreenLocation(point);
                if (latLng.latitude != 0 && latLng.longitude != 0) {
                    if (TextUtils.isEmpty(searchText)){
                        //地图状态改变结束，请求网络操作，获取店铺信息
                        getLocationInfo(latLng.latitude, latLng.longitude, null);
                    }else {
                        getLocationInfo(latLng.latitude, latLng.longitude, searchText);
                    }
                }
            }

            @Override
            public void onMapStatusChange(MapStatus arg0) {
                // TODO Auto-generated method stub
            }
        });
    }
    @Override
    protected void initData() {
        RxBus.getDefault().toObservable(FirstEvent.class)
                //在io线程进行订阅，可以执行一些耗时操作
                .subscribeOn(Schedulers.io())
                //在主线程进行观察，可做UI更新操作
                .observeOn(AndroidSchedulers.mainThread())
                //观察的对象
                .subscribe(new Action1<FirstEvent>() {
                    @Override
                    public void call(FirstEvent firstEvent) {
                        if (firstEvent.getCode().equals("location")) {
                            Double lat = Double.parseDouble(firstEvent.getLatitude());
                            Double log = Double.parseDouble(firstEvent.getLongitude());
                            getLocationInfo(lat, log, null);
                        }
                    }
                });
    }

    @Override
    protected int getLayoutId() {
        return 0;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.reset_location_iv:
                //重新定位
                mBaiduMap.clear();
                BaiduMapHelper
                        .getInstance()
                        .init(baiduMapView)
                        .params(getHoldingActivity())
                        .showLocation();
                break;
            case R.id.map_trade_search_ll:
                break;
        }
    }

    /**
     * 地图状态开始改变就开始执行动画start
     */
    private void startAnima() {
        final TranslateAnimation animation = new TranslateAnimation(0, 0, 0, -50);
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(200);//设置动画持续时间
        animation.setRepeatCount(0);//设置重复次数
        animation.setFillAfter(true);
        middleIv.startAnimation(animation);
    }

    /**
     * 地图状态改变结束就开始执行动画finish
     */
    private void startAnima2() {
        final TranslateAnimation animation2 = new TranslateAnimation(0, 0, -50, 0);
        animation2.setInterpolator(new LinearInterpolator());
        animation2.setDuration(200);//设置动画持续时间
        animation2.setRepeatCount(0);//设置重复次数
        animation2.setFillAfter(true);
        middleIv.startAnimation(animation2);
    }

    @Override
    public void showSuccessMsg(String s, NearByTradeAreaBean nearByTradeAreaBean) {
        tradeAreaList = nearByTradeAreaBean.getData();
        Point point = new Point();
        int[] location = new int[2];
        middleIv.getLocationOnScreen(location);
        point.x = (int) tradeAreaList.get(0).getLatitude();
        point.y = (int) tradeAreaList.get(0).getLongitude();
        baiduMapView.setZoomControlsPosition(point);
        /**
         添加覆盖物
         */
        addMapIcon(tradeAreaList);
    }

    @Override
    public void showErrorMsg(String s) {
    }

    @Override
    public void getNearbyTradeArea(NearByTradeAreaBean nearByTradeAreaBean) {

    }

    private void getLocationInfo(double latitude, double longitude, String searchResult) {
        //网络操作，获取商圈店铺信息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("latitude", latitude);
        jsonObject.put("longitude", longitude);
        jsonObject.put("name", searchResult);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        nearByTradeAreaPresenter.deliverNearTradeData(body);
    }

    private void addMapIcon(List<NearByTradeAreaBean.DataBean> tradeAreaList) {
        /**
         * 每次添加覆盖物之前都要先移除覆盖物监听事件，防止点击事件多次执行
         */
        mBaiduMap.removeMarkerClickListener(onMarkerClickListener);
        mBaiduMap.clear();


        /**
         * 遍历外层商圈
         */
        for (int i = 0; i < tradeAreaList.size(); i++) {
            Bundle bundle = new Bundle();
            Marker marker;
            NearByTradeAreaBean.DataBean dataBean = tradeAreaList.get(i);
            //定义Maker坐标点
            LatLng point = new LatLng(dataBean.getLatitude(), dataBean.getLongitude());
            //构建Marker图标
            int icon = R.mipmap.map_shop_circle_ic;
            //转换为BitMap
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(icon);
            //构建MarkerOption，用于在地图上添加Marker
            OverlayOptions option = new MarkerOptions()
                    .position(point)
                    .perspective(true)
                    .icon(bitmap);
            //在地图上添加Marker，并显示
            marker = (Marker) mBaiduMap.addOverlay(option);

            bundle.putSerializable("trade_click", dataBean);
            marker.setExtraInfo(bundle);
            StoreInfoList = tradeAreaList.get(i).getSimpleStoreInfoList();
            //获取商圈状态   -1 ：未认购 ；0 ：申请中；1 ：已认购 ；
            String TradeAreaState = tradeAreaList.get(i).getState();
            /*
             遍历内层店铺
             */
            for (int j = 0; j < StoreInfoList.size(); j++) {
                Bundle bundle1 = new Bundle();
                Marker marker1;
                NearByTradeAreaBean.DataBean.SimpleStoreInfoListBean dataBean1 = StoreInfoList.get(j);
                //定义Maker坐标点
                LatLng point1 = new LatLng(dataBean1.getLatitude(), dataBean1.getLongitude());
                //构建Marker图标
                int icon1 = R.mipmap.map_shop_ic;
                //转换为BitMap
                BitmapDescriptor bitmap1 = BitmapDescriptorFactory
                        .fromResource(icon1);
                //构建MarkerOption，用于在地图上添加Marker
                OverlayOptions option1 = new MarkerOptions()
                        .position(point1)
                        .perspective(true)
                        .icon(bitmap1);
                //在地图上添加Marker，并显示
                marker1 = (Marker) mBaiduMap.addOverlay(option1);
                bundle1.putSerializable("shop_click", dataBean1);
                marker1.setExtraInfo(bundle1);
            }
        }
        /**
         * 覆盖物点击事件
         */
        mBaiduMap.setOnMarkerClickListener(onMarkerClickListener);

    }
    public Dialog createshopInfoDialog(NearByTradeAreaBean.DataBean.SimpleStoreInfoListBean infoListBean) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View v = inflater.inflate(R.layout.map_shop_dialog, null);// 得到加载view
        ImageView cancel = (ImageView) v.findViewById(R.id.cancel_dialog);// 提示文字
        mDCover = (ImageView) v.findViewById(R.id.cover);
        mDShopImg = (ImageView) v.findViewById(R.id.shop_img);
        mDName = (TextView) v.findViewById(R.id.name);
        mDRatingBar = (RatingBar) v.findViewById(R.id.ratingBar);
        mDScore = (TextView) v.findViewById(R.id.score);
        mDGoodsNum = (TextView) v.findViewById(R.id.goods_num);
        mDAddress = (TextView) v.findViewById(R.id.address);
        mDEnterShop = (Button) v.findViewById(R.id.enter_store);
        mPayBound = (ImageView) v.findViewById(R.id.is_pay_bond_iv);

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDEnterShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                //进入店铺
                SkipUtils.toMarketDetail(getHoldingActivity());
            }
        });
        mPayBound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        Dialog dialog = new Dialog(getContext(), R.style.MyDialogStyle);// 创建自定义样式dialog
//      loadingDialog.setCancelable(true);// 不可以用“返回键”取消
        dialog.setContentView(v);// 设置布局
        return dialog;

    }

    /**
     * 自定义覆盖物监听类，用来控制覆盖物的监听与取消监听
     */
    BaiduMap.OnMarkerClickListener onMarkerClickListener = new BaiduMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Bundle bundle = marker.getExtraInfo();
            if (bundle != null) {
                //外层商圈点击事件
                NearByTradeAreaBean.DataBean dataBean =
                        (NearByTradeAreaBean.DataBean) bundle.getSerializable("trade_click");
                if (dataBean != null) {
                    switch (dataBean.getState()) {
                        case "-1":
                            Toasty.info(getHoldingActivity(), "该商圈未开放").show();
                            break;
                        case "0":
                            Toasty.info(getHoldingActivity(), "该商圈审核中，敬请期待").show();
                            break;
                        case "1":
                            Log.e("shanquanid :",dataBean.getId());
                            Log.e("lat :",dataBean.getLatitude()+"");
                            Log.e("lon :",dataBean.getLongitude()+"");
                            Log.e("商圈状态 :",dataBean.getState()+"");
                            String tradeId= dataBean.getId();
                            double lat= dataBean.getLatitude();
                            double lon= dataBean.getLongitude();
                            String tradePhone= dataBean.getPhone();


                            SkipUtils.toTradeAreaSearchPage(getHoldingActivity(),tradeId,lat,lon,tradePhone);
                            break;
                    }
                }
                //内层店铺点击事件
                NearByTradeAreaBean.DataBean.SimpleStoreInfoListBean infoListBean =
                        (NearByTradeAreaBean.DataBean.SimpleStoreInfoListBean) bundle.getSerializable("shop_click");

                if (infoListBean != null) {
                    //展示弹窗
                    mDialog = createshopInfoDialog(infoListBean);
                    mDialog.show();
                }
            }
            return false;
        }
    };
}
